//
//  BSUserAccountViewModel.swift
//  mySwiftWeibo
//
//  Created by apple on 16/7/22.
//  Copyright © 2016年 itcast沈庆伟. All rights reserved.
//

import UIKit

import AFNetworking
/*
负责处理BSUserAccount的业务逻辑
网络请求
字典转模型
保存模型到沙盒中
沙盒加载模型到内存中-userAccount属性
*/


class BSUserAccountViewModel: NSObject {

    ///userAccount,以后要访问账号只需要访问这个属性
    var userAccount: BSUserAccount?
    
    ///用户是否登录的属性
    var userLogin: Bool{
        get{
            //有账号就表示登录
            return userAccount != nil
        }
    }
    
    ///单例
    static let sharedUserAccountViewModel: BSUserAccountViewModel=BSUserAccountViewModel()
    
    ///账号保存的路径
    let userAccountFile=NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
    
    override init() {
        //读取沙盒中的账号
        super.init()
        
        //对象方法-在创建对象时候执行
        //保存到内存
        userAccount=loadAccount()
    }
    
    ///获取用户名称和头像
    func loadUserInfo(completion: (error: NSError?) -> ()){
        //过多的if let会造成嵌套太多,可以使用守卫
        guard let access_token = userAccount?.access_token else{
            //没有值才进来
            print("没有access_token,不发网络请求")
            return
        }
        
        guard let uid = userAccount?.uid else{
            //没有值才进来
            print("没有uid,不发网络请求")
            return
        }
        
        //来到这里,access_tiken和uid都有值,后面可以一直使用access_token
        
        // urlString
        let urlString = "2/users/show.json"
        
        // 参数
        let parameters = [
            "access_token": access_token,
            "uid": uid
        ]
        
        // 发送请求
        BSNetWorkTool.sharedNetworkTool.GET(urlString, parameters: parameters, progress: nil, success: { (_, responseObjce) -> Void in
           
            // 获取用户名称和头像地址
            let dict = responseObjce as? [String: AnyObject]
            let screen_name = dict?["screen_name"] as? String
            let avatar_large = dict?["avatar_large"] as? String
            
            // 给userAccount赋值
            self.userAccount?.screen_name = screen_name
            self.userAccount?.avatar_large = avatar_large
            
            // 将模型重新保存到沙盒中
            self.saveUserAccount(self.userAccount!)
            
            //告诉调用的人获取到了数据
            completion(error: nil)
            }) { (_, error) -> Void in
                print("请求用户数据失败: \(error)")
                // 告诉调用的人获取数据失败了
                completion(error: error)
        }
    }
    
    ///去服务器请求access_token
    func loadAccessToken(code: String, completion: (error: NSError?) -> Void){

        let URLString="https://api.weibo.com/oauth2/access_token"
        let parameter=[
            "client_id":client_id,
            "client_secret":app_secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        
        //post请求
        BSNetWorkTool.sharedNetworkTool.POST(URLString, parameters: parameter, progress: nil, success: { (_, responseObject) -> Void in
            //print("responseObject: \(responseObject)")
            /*
            "access_token" = "2.00YJnIMG3bO98Babd589ef208zw2_B";
            "expires_in" = 152208;
            "remind_in" = 152208;
            uid = 5676208596;
            */
            //字典转模型-先转字典
            let dict = responseObject as! [String: AnyObject]
            self.userAccount = BSUserAccount(dict: dict)
            print("userAccount = \(self.userAccount)")
            
            //保存到沙盒中
            self.saveUserAccount(self.userAccount!)
            
            //回调
            //测试
            //completion(error: NSError(domain: "aa", code: 10000, userInfo: ["a" : "b"]))
            completion(error: nil)
            }) { (_, error) -> Void in
                
                completion(error: error)
        }
    }
    
    ///保存模型到沙盒中
    private func saveUserAccount(userAccount: BSUserAccount){
        NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.userAccountFile)
    }
    
    ///加载沙盒中的账号
    private func loadAccount() -> BSUserAccount?{
        let account=NSKeyedUnarchiver.unarchiveObjectWithFile(userAccountFile) as? BSUserAccount
        
        /*
        如果沙盒中有账号需要判断是否过期
        NSDate():当前时间
        account?.expiresDate 2016-07-23
        2016-07-23 > 2016-07-22
        */
        //account?.expiresDate=NSDate(timeIntervalSinceNow: -100)
        if account != nil && account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            print("没有过期的账号")
            return account
        }
        print("过期的账号")
        return nil
    }
}
